package com.tt.vtg.scenario.task;

import com.tt.vtg.scenario.redis.JedisTemplate;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

public class CheckOrderStatusTask implements Callable<CheckOrderEntity>{
    public static final int PROCESSING = 0;
    public static final int SUCCESS = 1;
    public static final int FAILED = 2;

    private String recordId;

    public CheckOrderStatusTask(String recordId){
        this.recordId = recordId;
    }

    /*
    *  If status is 'processing', try 5 seconds to get status.
    *  Then return the actual status.
    *
    * */
    public CheckOrderEntity call() throws Exception {
        CheckOrderEntity checkedEntity = new CheckOrderEntity();
        int tryConut=0;
        for(;;){
            ++tryConut;

            JedisTemplate.execute(j->{
                List<String> lst = j.hmget(recordId, "status", "result");
//                System.out.println("CheckOrderStatusTask @ status:" + lst.get(0));
//                System.out.println("CheckOrderStatusTask @ result:" + lst.get(1));
                checkedEntity.setStatus(Integer.valueOf((lst.get(0)==null ? String.valueOf(FAILED) : lst.get(0))));
                checkedEntity.setResult(lst.get(1));

                return null;
            });

            if(checkedEntity.getStatus() != PROCESSING || tryConut >= 5){
                return checkedEntity;
            }

            TimeUnit.SECONDS.sleep(1);
        }
    }
}
